<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\components\Helper;
use common\components\IDValidator\IDValidator;
use common\components\Upload;
use common\models\business\BusinessAdress;
use common\models\business\BusinessPerson;
use Yii;
use common\models\business\BusinessFarmers;
use backend\modules\business\models\BusinessFarmersSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * FarmersController implements the CRUD actions for BusinessFarmers model.
 */
class FarmersController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessFarmers models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessFarmersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessFarmers model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessFarmers model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessFarmers();
        if ($model->load(Yii::$app->request->post())){
            $postdata = Yii::$app->request->post();
            if(false !== $iphoto = Upload::upload($model,'identity_photo')){
                $model->setAttribute('identity_photo',$iphoto);
            }
            if(false !== $sphoto = Upload::upload($model,'pighousephoto')){
                $model->setAttribute('pighousephoto',$sphoto);
            }
            if(false !== $photo = Upload::upload($model,'photo')){
                $model->setAttribute('photo',$photo);
            }
            if(!Yii::$app->request->post('farmhouseid')){
                $model->setAttribute('farmhouseid',0);
            }

            if($model->ischeckiendtity == 0){
                if(!Helper::checkIdCard($postdata['BusinessFarmers']['identity'])){
                    return $this->dialog('身份证格式错误');
                }
            }


            if($model->save()){
                if(!empty($postdata['BusinessFarmers']['pigs'])) {
                    $personobj =  BusinessPerson::findOne($model->introducer);
                    if(is_object($personobj)){
                        $headperson = $personobj->name;
                    }else{
                        return $this->dialog('请指定有效的业务巡检人员');
                    }
                    
//                    $headperson = BusinessPerson::findOne($model->introducer)->name;
                    foreach ($postdata['BusinessFarmers']['pigs'] as $key => $row) {
                        $checkLivery = (new Query())->select('id,livery,no,liveryname')->from(BusinessPig::tableName())->where('id=:id',[':id'=>$row])->one();

                        if($checkLivery['livery'] != 0 && $checkLivery['livery'] != $model->id){
                            return $this->dialog('仔猪'.$checkLivery['no'].'已被农户'.$checkLivery['liveryname'].'代养');
                        }
                        //更新仔猪的代养农户，顺带将更新仔猪的业务人员
                        $data = [
                            'livery' => $model->id,
                            'liveryname' => $model->name,
                            'headpersonid' => $model->introducer,
                            'headperson' => $headperson
                        ];
                        Yii::$app->db->createCommand()->update(BusinessPig::tableName(), $data, 'id=:id', [':id' => $row])
                            ->execute();
                    }
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->dialog($this->checkError($model));
        }else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessFarmers model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())){
            $postdata = Yii::$app->request->post();
            $model->setScenario('update');
            if(false !== $iphoto = Upload::upload($model,'identity_photo')){
                $model->setAttribute('identity_photo',$iphoto);
            }
            if(false !== $sphoto = Upload::upload($model,'pighousephoto')){
                $model->setAttribute('pighousephoto',$sphoto);
            }
            if(false !== $photo = Upload::upload($model,'photo')){
                $model->setAttribute('photo',$photo);
            }


            if($model->ischeckiendtity == 0){
                if(!Helper::checkIdCard($postdata['BusinessFarmers']['identity'])){
                    return $this->dialog('身份证格式错误');
                }
            }

            if($model->save()){

                $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                    ->where('livery=:id',[':id'=>$model->id])
                    ->all();
                if(!empty($pids)){
                    $pids = ArrayHelper::getColumn($pids,'id');
                }else{
                    $pids = [];
                }
                if(!empty($postdata['BusinessFarmers']['pigs'])){
                    $diff = array_diff($pids,$postdata['BusinessFarmers']['pigs']);
                    $personobj =  BusinessPerson::findOne($model->introducer);
                    if(is_object($personobj)){
                        $headperson = $personobj->name;
                    }else{
                        return $this->dialog('请指定有效的业务巡检人员');
                    }
                    foreach ($postdata['BusinessFarmers']['pigs'] as $key => $row){
                        $checkLivery = (new Query())->select('id,livery,no,liveryname')->from(BusinessPig::tableName())->where('id=:id',[':id'=>$row])->one();

                        if($checkLivery['livery'] != 0 && $checkLivery['livery'] != $model->id){
                            return $this->dialog('仔猪'.$checkLivery['no'].'已被农户'.$checkLivery['liveryname'].'代养');
                        }
                        //更新仔猪的代养农户，顺带将更新仔猪的业务人员
                        $data = [
                            'livery' => $model->id,
                            'liveryname' => $model->name,
                            'headpersonid' => $model->introducer,
                            'headperson' => $headperson
                        ];
                        Yii::$app->db->createCommand()->update(BusinessPig::tableName(), $data, 'id=:id', [':id' => $row])
                            ->execute();
                    }
                }else{
                    $diff = $pids;
                }

                //去掉删除的
                foreach ($diff as $key => $row){
                    Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['livery'=>0,'liveryname'=>'','headpersonid'=>0,'headperson'=>''],'id=:id',[':id'=>$row])
                        ->execute();
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->dialog($this->checkError($model));
            }
        } else {

            $pids = (new Query())->select('id,no')->from(BusinessPig::tableName())
                ->where('livery=:id',[':id'=>$model->id])
                ->all();
            $ids = [];
            foreach ($pids as $key => $row){
                $ids[$row['id']] = '['.$row['id'].']'.$row['no'].']';
            }

            return $this->render('update', [
                'model' => $model,
                'ids' => $ids
            ]);
        }
    }


    /**
     * Deletes an existing BusinessFarmers model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }



    public function actionRelation($id)
    {
        $searchModel = new BusinessFarmersSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

        $relation = BusinessFarmers::findOne($id)->farmerRelation;
        return $this->render('relation');
    }


    /**
     * Finds the BusinessFarmers model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessFarmers the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessFarmers::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }



    public function actionAddressData($id)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $data =  BusinessAdress::sons($id);
        if($data[0]['type'] == BusinessAdress::TYPE_ZHEN){
            $data = array_merge([['name'=>'选择对应的镇','id'=>'']],$data);
        }else{
            $data = array_merge([['name'=>'选择对应的村','id'=>'']],$data);
        }
        return $data;
    }


    /**
     * @param $id
     * @return array
     * 搜索经纬度
     */
    public function actionSearchLocation($id)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $add = BusinessAdress::findOne($id);
        return [
            'lat' => $add->lat,
            'lng' => $add->lng
        ];
    }


    /**
     * @return string
     * 批量更新巡检员
     */
    public function actionSetPerson()
    {
        if(Yii::$app->request->isPost){
            $ids = Yii::$app->request->post('ids');
            $introducer = Yii::$app->request->post('introducer');
            if(empty($ids)){
                return $this->dialog('请选择对应的农户');
            }

            if(empty($introducer)){
                return $this->dialog('请选择巡检员');
            }
            $ids = explode(',',$ids);
            foreach ($ids as $key => $row){
                $res = Yii::$app->db->createCommand()->update(BusinessFarmers::tableName(),['introducer'=>$introducer],'id=:id')
                    ->bindValues([':id'=>$row])
                    ->execute();
            }
            return $this->dialog('更新成功');
        }
    }



    //批量设置审核
    public function actionSetpass()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $idstr = implode(',',$ids);
            Yii::$app->db->createCommand('update '.BusinessFarmers::tableName().' set status=:status where id in('.$idstr.')')
                ->bindValues([':status'=>BusinessFarmers::STATUS_AGREE])
                ->execute();
            return \GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的农户','status'=>1]);
    }


    /**
     * @param $id
     * @return string
     * 根据输入的仔猪的编号，获取巡检员
     */
    public function actionGetPersonByPig($id)
    {
        $person = (new Query())->select('headperson,headpersonid')->from(\common\models\business\BusinessPig::tableName())->where('id=:id',[':id'=>$id])->one();
        if(empty($person)){
            return json_encode(['status'=>1]);
        }
        return json_encode(['person'=>$person,'status'=>0]);
    }



}
